import React, {Component} from "react";
import {
    DeviceEventEmitter,
    Image,
    PermissionsAndroid,
    Picker,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import chjStyle from "../../../CustomStyle";
import ModuleCommonHeader from "../../module/ModuleCommonHeader";
import {Col, Row} from "react-native-easy-grid";
import Util from "../../Util";
import {Actions} from "react-native-router-flux";
import ImagePicker from "react-native-image-crop-picker";

const styles = StyleSheet.create({
    col: {
        height: chjStyle.getActualSizeInVertical(375),
    },
    grid: {
        backgroundColor: 'rgba(255, 255, 255, 255)',
        height: chjStyle.getActualSizeInVertical(375),
        borderColor: '#ccc',
        borderBottomWidth: 1,
        borderRightWidth: 1,
    }
});

const optionArray = ['null', '小于100mm×100mm', '100mm×100mm和200mm×300mm之间', '大于200mm×300mm'];

export default class CommonPhotoSelection extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataModel: Util.decodePhotoString(this.props.optionString)
        };
        this._showImagePicker = this._showImagePicker.bind(this);
        this._savePic = this._savePic.bind(this);
    }

    componentDidMount() {
        // 检查权限
        if (Platform.OS === 'android') {
            this.requestCameraPermission();
        }
    }

    async requestCameraPermission() {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.CAMERA,
                {
                    'title': '需要摄像头权限',
                    'message': '缺少权限的话无法完成此操作'
                }
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED || granted === true) {
                this.requestReadStoragePermission();
            } else {
                this.onCancel();
            }
        } catch (err) {
            this.onCancel();
        }
    }

    async requestReadStoragePermission() {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                {
                    'title': '需要读取内存卡权限',
                    'message': '缺少权限的话无法完成此操作'
                }
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED || granted === true) {
                this.requestWriteStoragePermission();
            } else {
                this.onCancel();
            }
        } catch (err) {
            this.onCancel();
        }
    }

    async requestWriteStoragePermission() {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                {
                    'title': '需要写入内存卡权限',
                    'message': '缺少权限的话无法完成此操作'
                }
            );
            if (granted === PermissionsAndroid.RESULTS.GRANTED || granted === true) {
                // ok;
            } else {
                this.onCancel();
            }
        } catch (err) {
            this.onCancel();
        }
    }

    render() {
        var content = [];
        for (var i = 0; i < this.state.dataModel.length; i += 2) {
            content.push(
                <Row>
                    {this.getRowGrids(this.state.dataModel[i], (i + 1 < this.state.dataModel.length) ? this.state.dataModel[i + 1] : null, i)}
                </Row>
            );
        }

        return (
            <View style={[chjStyle.mainContainer, {backgroundColor: '#303030'}]}>
                <ModuleCommonHeader title={this.props.title} leftText='取消' clickedLeft={this.onCancel.bind(this)}
                                    rightText='确定' clickedRight={this.onResult.bind(this)}/>
                <ScrollView style={chjStyle.recordContainer}>
                    {content}
                </ScrollView>
            </View>
        );
    }

    getRowGrids(gridData1, gridData2, i) {
        const rowArray = [];
        rowArray.push(
            this.renderGrid(gridData1, i)
        );
        if (gridData2 !== null) {
            rowArray.push(
                this.renderGrid(gridData2, i + 1)
            );
        } else {
            rowArray.push(
                <Col>
                    <View style={{height: chjStyle.getActualSizeInVertical(375), backgroundColor: '#303030'}}/>
                </Col>
            )
        }
        return rowArray;
    }

    renderGrid(data, index) {
        return (
            <Col>
                <TouchableOpacity style={styles.grid}
                                  onPress={() => this._showImagePicker(data, index)}>
                    <Image style={{
                        width: chjStyle.getActualSizeInHorizontal(375),
                        height: chjStyle.getActualSizeInVertical(375)
                    }}
                           source={{uri: data.localPic}} ref={'img' + index} resizeMode='cover'/>
                    <Text style={{
                        color: data.localPic !== 'null' ? '#f91' : '#888',
                        backgroundColor: 'rgba(0,0,0,0)',
                        position: 'absolute',
                        left: 2,
                        top: 2,
                        width: chjStyle.getActualSizeInHorizontal(300),
                        fontSize: chjStyle.getActualFontSize(28)
                    }}
                          ref={'txt' + index}>{data.name}</Text>
                    {
                        this.renderPicker(data, index)
                    }
                </TouchableOpacity>
            </Col>
        );
    }

    renderPicker(data, index) {
        if (data.extra) {
            if (Platform.OS === 'ios') {
                return (<TouchableOpacity
                    onPress={() => {
                        const options = [];
                        for (let i = 0; i < optionArray.length; i++) {
                            options.push({
                                name: optionArray[i],
                                value: optionArray[i]
                            });
                        }
                        DeviceEventEmitter.emit('showDialog', options, (value) => this.onPickedData2(data, value, index));
                    }}
                    style={{
                        position: 'absolute',
                        color: '#303030',
                        backgroundColor: '#f91',
                        top: chjStyle.getActualSizeInVertical(375 - 88),
                        left: chjStyle.getActualSizeInHorizontal(0),
                        width: chjStyle.getActualSizeInHorizontal(375),
                        height: chjStyle.getActualSizeInVertical(88)
                    }}
                >
                    <Text style={{
                        backgroundColor: 'rgba(0,0,0,0)',
                        color: '#fff',
                    }}>{data.extra}</Text>
                </TouchableOpacity>);
            }
            return (<Picker
                style={{
                    position: 'absolute',
                    color: '#303030',
                    backgroundColor: '#f91',
                    top: chjStyle.getActualSizeInVertical(375 - 88),
                    left: chjStyle.getActualSizeInHorizontal(0),
                    width: chjStyle.getActualSizeInHorizontal(375),
                    height: chjStyle.getActualSizeInVertical(88)
                }}
                mode={'dialog'} prompt={'缺陷程度'} onValueChange={(value) => this.onPickedData(data, value, index)}
                selectedValue={data.extra}>
                {
                    optionArray.map((item, i) => this.renderExpenseItem(item, i))
                }
            </Picker>);
        }
    }

    renderExpenseItem(item, i) {
        return <Picker.Item label={item} value={item}/>;
    }

    onPickedData2(data, value, index) {
        data.extra = value;
        this.setState({
            dataModel: this.state.dataModel
        });
        if (value !== 'null') {
            const to = setTimeout(() => {
                this._showImagePicker(data, index);
                to && clearTimeout(to);
            }, 600);
        }
    }

    onPickedData(data, value, index) {
        data.extra = value;
        this.setState({
            dataModel: this.state.dataModel
        });
        if (value !== 'null') {
            this._showImagePicker(data, index);
        }
    }

    _showImagePicker(data, index) {
        console.log('CommonPhotoSelection _showImagePicker    ' + JSON.stringify(data));
        const width = 1080;
        const height = 720;
        const option = {
            width,
            height,
            cropping: true
        };
        const handle = [];
        handle.push({
            name: '照片', act: () => {
                ImagePicker.openCamera(option).then(image => {
                    this._savePic(data, image);
                });
            }
        });
        handle.push({
            name: '相册', act: () => {
                ImagePicker.openPicker(option).then(image => {
                    this._savePic(data, image);
                });
            }
        });
        handle.push({
            name: '删除', act: () => {
                data.localPic = 'null';
                this.props.optionString = Util.encodePhotoModel(this.state.dataModel);
                this.setState({
                    dataModel: this.state.dataModel
                });
            }
        });
        handle.push({
            name: '取消', act: () => {

            }
        });
        this._setDialog(handle, result => {
            result.act();
        });
    }

    _savePic(data, image) {
        console.log('CommonPhotoSelection _savePic    ' + JSON.stringify(image));
        data.localPic = image.path;
        this.props.optionString = Util.encodePhotoModel(this.state.dataModel);
        this.setState({
            dataModel: this.state.dataModel
        });
    }

    _setDialog(array, select) {
        Actions.dialog({
            array,
            select,
        });
    }

    onCancel() {
        Actions.pop();
    }

    onResult() {
        Actions.pop();
        this.props.onResultListener(Util.encodePhotoModel(this.state.dataModel));
    }
}
